package com.sk.weichat.ui.message.multi;

import android.content.Context;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SectionIndexer;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.sk.weichat.AppConstant;
import com.sk.weichat.R;
import com.sk.weichat.Reporter;
import com.sk.weichat.adapter.GroupMembersHeadAdapter;
import com.sk.weichat.bean.Friend;
import com.sk.weichat.bean.RoomMember;
import com.sk.weichat.bean.SetManager;
import com.sk.weichat.db.InternationalizationHelper;
import com.sk.weichat.db.dao.FriendDao;
import com.sk.weichat.db.dao.RoomMemberDao;
import com.sk.weichat.helper.AvatarHelper;
import com.sk.weichat.helper.DialogHelper;
import com.sk.weichat.sortlist.BaseSortModel;
import com.sk.weichat.sortlist.SideBar;
import com.sk.weichat.sortlist.SortHelper;
import com.sk.weichat.ui.base.BaseActivity;
import com.sk.weichat.ui.base.CoreManager;
import com.sk.weichat.util.AppUtils;
import com.sk.weichat.util.AsyncUtils;
import com.sk.weichat.util.ListUtil;
import com.sk.weichat.util.SearchUtils;
import com.sk.weichat.util.ToastUtil;
import com.sk.weichat.util.ViewHolder;
import com.sk.weichat.view.SelectionFrame;
import com.xuan.xuanhttplibrary.okhttp.HttpUtils;
import com.xuan.xuanhttplibrary.okhttp.callback.BaseCallback;
import com.xuan.xuanhttplibrary.okhttp.result.ObjectResult;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;
import okhttp3.Call;

/**
 * 设置 &&  取消 管理员，隐身人，监控人
 */
public class SetManagerActivity extends BaseActivity {
    private String roomId;
    private int role;
    private String roomJid;

    private EditText mEditText;
    private LinearLayout ll_main;
    private RelativeLayout rt_title;
    private RelativeLayout layout_search;

    private ListView mListView;
    private SideBar mSideBar;
    private TextView mTextDialog;
    private SetManagerAdapter mSetManagerAdapter;
//    private List<SetManager> setManagerList;
    private List<BaseSortModel<RoomMember>> mSortRoomMember = new ArrayList<>();
    private List<BaseSortModel<RoomMember>> mSortHeadRoomMember = new ArrayList<>();
    private List<BaseSortModel<RoomMember>> sortedList = new ArrayList<>();
//    private Map<String, String> mRemarksMap = new HashMap<>();
    private View headView;
    private RecyclerView recy_head;
    private GroupMembersHeadAdapter membersHeadAdapter;

//    private boolean isCanClick = true;//是否可点击头部管理员列表 预防连续点击 状态没变得那么快导致数组溢出崩溃
//    private boolean isCanListClick = true;//是否可点击成员列表 预防连续点击 状态没变得那么快导致数组溢出崩溃
    public static void start(Context ctx, String roomId, String roomJid, int role) {
        Intent intent = new Intent(ctx, SetManagerActivity.class);
        intent.putExtra("roomId", roomId);
        intent.putExtra("role", role);
        intent.putExtra(AppConstant.EXTRA_USER_ID, roomJid);
        ctx.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_set_manager);
        if (getIntent() != null) {
            roomId = getIntent().getStringExtra("roomId");
            role = getIntent().getIntExtra("role", RoomMember.ROLE_MANAGER);
            roomJid = getIntent().getStringExtra(AppConstant.EXTRA_USER_ID);
        }
        initActionBar();
        loadData();
        initView();
    }

    private void initActionBar() {
        getSupportActionBar().hide();
        findViewById(R.id.iv_title_left).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        int titleId;
        switch (role) {
            case RoomMember.ROLE_MANAGER:
                titleId = R.string.design_admin;
                break;
            case RoomMember.ROLE_INVISIBLE:
                titleId = R.string.set_invisible;
                break;
            case RoomMember.ROLE_GUARDIAN:
                titleId = R.string.set_guardian;
                break;
            default:
                Reporter.unreachable();
                return;
        }
        TextView textView = findViewById(R.id.tv_title_center);
        textView.setText(titleId);
    }

    private void loadData() {

        if (!DialogHelper.isShowing()) {
            DialogHelper.showDefaulteMessageProgressDialog(this);
        }
        AsyncUtils.doAsync(this, e -> {
            Reporter.post("加载数据失败，", e);
            AsyncUtils.runOnUiThread(this, ctx -> {
                DialogHelper.dismissProgressDialog();
                ToastUtil.showToast(ctx, R.string.data_exception);
            });
        }, c -> {
            List<RoomMember> data = RoomMemberDao.getInstance().getRoomMember(roomId);
            Map<String, Integer> existMap = new HashMap<>();
            sortedList = SortHelper.toSortedModelList(data, existMap, RoomMember::getShowName);
            c.uiThread(r -> {
                DialogHelper.dismissProgressDialog();
                if (mSortRoomMember != null) {
                    mSortRoomMember.clear();
                }
                if (mSortHeadRoomMember!=null){
                    mSortHeadRoomMember.clear();
                }
                mSideBar.setExistMap(existMap);
                if (!ListUtil.isListEmpty(sortedList)) {
                    mSideBar.searchByFirstStr(sortedList.get(0).getFirstLetter());
                }
                for (int i = 0; i <sortedList.size(); i++) {
                    if (sortedList.get(i).getBean().getRole()!=1){
                        if (sortedList.get(i).getBean().getRole()==2){
                            mSortHeadRoomMember.add(sortedList.get(i));
                        }else {
                            mSortRoomMember.add(sortedList.get(i));
                        }
                    }
                }
                if (mSortHeadRoomMember.size()>0&&role!=RoomMember.ROLE_INVISIBLE){//指定隐身人 不显示群主和管理员
                    membersHeadAdapter.notifyDataSetChanged();
                    mListView.addHeaderView(headView);
                }
                mSetManagerAdapter.notifyDataSetChanged();
            });
        });
    }


    private void initView() {
        ll_main = findViewById(R.id.ll_main);
        rt_title = findViewById(R.id.rt_title);
        layout_search = findViewById(R.id.layout_search);
        layout_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new SearchUtils(SetManagerActivity.this, rt_title,
                        ll_main, "请输入昵称或备注名", sortedList, new SearchUtils.onItemClickOListener() {
                    @Override
                    public void onSearchItemClick(RoomMember roomMember) {
                        if (roomMember.getRole() == role) {
                            // 如果已经是这个身份，再点击就是取消，
                            if (role == RoomMember.ROLE_MANAGER) {
                                // 取消管理员，保留旧代码，
                                cancelManager(roomId, roomMember);
                            } else {
                                // 取消隐身人，监控人，
                                cancelRole(roomId, roomMember, role);
                            }
                        } else {
                            if (role == RoomMember.ROLE_MANAGER) {
                                // 设置管理员，保留旧代码，
                                setManager(roomId, roomMember);
                            } else {
                                // 设置隐身人，监控人，
                                setRole(roomId, roomMember, role);
                            }
                        }
                    }
                }).showSearchBar();
            }
        });

        mListView = findViewById(R.id.set_manager_lv);
        headView = LayoutInflater.from(this).inflate(R.layout.layout_recy, mListView, false);
        TextView tv_title = headView.findViewById(R.id.tv_title);
        tv_title.setVisibility(View.VISIBLE);
        tv_title.setText("管理员");
        recy_head = headView.findViewById(R.id.recy_had_add);
        membersHeadAdapter = new GroupMembersHeadAdapter(mSortHeadRoomMember);
        recy_head.setLayoutManager(new LinearLayoutManager(this));
        recy_head.setNestedScrollingEnabled(true);
        membersHeadAdapter.setHasStableIds(true);
        recy_head.setAdapter(membersHeadAdapter);

        mSetManagerAdapter = new SetManagerAdapter(this,mSortRoomMember);
        mListView.setAdapter(mSetManagerAdapter);
        mSideBar = (SideBar) findViewById(R.id.sidebar);
        mTextDialog = (TextView) findViewById(R.id.text_dialog);
        mSideBar.setTextView(mTextDialog);
        mSideBar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {
            @Override
            public void onTouchingLetterChanged(String s) {
                // 该字母首次出现的位置
                int position = mSetManagerAdapter.getPositionForSection(s.charAt(0));
                if (position != -1) {
                    mListView.setSelection(position);
                    showTextDialog(s);
                }
            }
        });

        membersHeadAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {

                if (!AppUtils.isFastClick()){
                    return;
                }
                RoomMember roomMember = mSortHeadRoomMember.get(position).getBean();
                if (roomMember.getUserId().equals(coreManager.getSelf().getUserId())) {
                    ToastUtil.showToast(SetManagerActivity.this, R.string.tip_cannot_set_self_role);
                    return;
                }
                if (roomMember.getRole() == role) {
                    // 如果已经是这个身份，再点击就是取消，
                    if (role == RoomMember.ROLE_MANAGER) {
                        // 取消管理员，保留旧代码，
                        cancelManager(roomId, roomMember);
                    } else {
                        // 取消隐身人，监控人，
                        cancelRole(roomId, roomMember, role);
                    }
                } else {
                    if (role == RoomMember.ROLE_MANAGER) {
                        // 设置管理员，保留旧代码，
                        setManager(roomId, roomMember);
                    } else {
                        // 设置隐身人，监控人，
                        setRole(roomId, roomMember, role);
                    }
                }
            }
        });
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                if (!AppUtils.isFastClick()){
                    return;
                }
                BaseSortModel<RoomMember> baseSortModel;
                if (mListView.getHeaderViewsCount()>0){//判断listview是否添加头部
                    baseSortModel = mSortRoomMember.get(position-1);
                }else {
                    baseSortModel = mSortRoomMember.get(position);
                }
                RoomMember roomMember = baseSortModel.bean;
                if (roomMember.getRole() == role) {
                    // 如果已经是这个身份，再点击就是取消，
                    if (role == RoomMember.ROLE_MANAGER) {
                        // 取消管理员，保留旧代码，
                        cancelManager(roomId, roomMember);
                    } else {
                        // 取消隐身人，监控人，
                        cancelRole(roomId, roomMember, role);
                    }
                } else {
                    if (role == RoomMember.ROLE_MANAGER) {
                        // 设置管理员，保留旧代码，
                        setManager(roomId, roomMember);
                    } else {
                        // 设置隐身人，监控人，
                        setRole(roomId, roomMember, role);
                    }
                }
            }
        });
    }

    //设置管理员
    private void setManager(String roomId, RoomMember roomMember) {
        HashMap<String, String> params = new HashMap<>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        params.put("roomId", roomId);
        params.put("touserId", roomMember.getUserId());
        params.put("type", String.valueOf(RoomMember.ROLE_MANAGER));
        DialogHelper.showDefaulteMessageProgressDialog(this);

        HttpUtils.get().url(coreManager.getConfig().ROOM_MANAGER)
                .params(params)
                .build()
                .execute(new BaseCallback<Void>(Void.class) {

                    @Override
                    public void onResponse(ObjectResult<Void> result) {
                        DialogHelper.dismissProgressDialog();
                        if (result.getResultCode() == 1) {
                            RoomMemberDao.getInstance().updateRoomMemberRole(roomId,roomMember.getUserId(),2);

                            EventBus.getDefault().post(new EventGroupStatus(10000, 0));
                            for (int i = 0; i < sortedList.size(); i++) {
                                if (sortedList.get(i).bean.getUserId() == roomMember.getUserId()){
                                    sortedList.get(i).bean.setRole(RoomMember.ROLE_MANAGER);
                                }
                            }
                            //改变列表状态
                            ChangeStatus();
                            Toast.makeText(SetManagerActivity.this, InternationalizationHelper.getString("JXRoomMemberVC_SetAdministratorSuccess"), Toast.LENGTH_SHORT).show();

                        } else if (!TextUtils.isEmpty(result.getResultMsg())) {
                            ToastUtil.showToast(SetManagerActivity.this, result.getResultMsg());
                        } else {
                            ToastUtil.showToast(SetManagerActivity.this, R.string.tip_server_error);
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        DialogHelper.dismissProgressDialog();
                        ToastUtil.showNetError(SetManagerActivity.this);
                    }
                });
    }

    private void setRole(String roomId, RoomMember roomMember, final int role) {
        Integer type;
        switch (role) {
            case RoomMember.ROLE_INVISIBLE:
                type = 4;
                break;
            case RoomMember.ROLE_GUARDIAN:
                type = 5;
                break;
            default:
                Reporter.unreachable();
                return;
        }
        HashMap<String, String> params = new HashMap<>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        params.put("roomId", roomId);
        params.put("touserId", roomMember.getUserId());
        params.put("type", type.toString());
        DialogHelper.showDefaulteMessageProgressDialog(this);

        HttpUtils.get().url(coreManager.getConfig().ROOM_UPDATE_ROLE)
                .params(params)
                .build()
                .execute(new BaseCallback<Void>(Void.class) {

                    @Override
                    public void onResponse(ObjectResult<Void> result) {
                        DialogHelper.dismissProgressDialog();
                        if (result.getResultCode() == 1) {
                            int tipContent;
                            switch (role) {
                                case RoomMember.ROLE_INVISIBLE: // 隐身人
                                    tipContent = R.string.tip_set_invisible_success;
                                    break;
                                case RoomMember.ROLE_GUARDIAN: // 监控人
                                    tipContent = R.string.tip_set_guardian_success;
                                    break;
                                default:
                                    Reporter.unreachable();
                                    return;
                            }
                            RoomMemberDao.getInstance().updateRoomMemberRole(roomId,roomMember.getUserId(),role);
                            // 保留旧代码，抛出去RoomInfoActivity统一处理，
                            EventBus.getDefault().post(new EventGroupStatus(10000, 0));
                            for (int i = 0; i < sortedList.size(); i++) {
                                if (sortedList.get(i).bean.getUserId()==roomMember.getUserId()){
                                    sortedList.get(i).bean.setRole(role);
                                }
                            }
                            ChangeStatus();
//                            loadData();
                            ToastUtil.showToast(SetManagerActivity.this, tipContent);

//                            roomMember.setRole(role);
//                            membersHeadAdapter.notifyDataSetChanged();
//                            mSetManagerAdapter.notifyDataSetChanged();
                        } else if (!TextUtils.isEmpty(result.getResultMsg())) {
                            ToastUtil.showToast(SetManagerActivity.this, result.getResultMsg());
                        } else {
                            ToastUtil.showToast(SetManagerActivity.this, R.string.tip_server_error);
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        DialogHelper.dismissProgressDialog();
                        ToastUtil.showNetError(SetManagerActivity.this);
                    }
                });
    }

    //取消管理员
    private void cancelManager(String roomId,RoomMember roomMember) {
        DialogHelper.showDefaulteMessageProgressDialog(this);
        HashMap<String, String> params = new HashMap<>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        params.put("roomId", roomId);
        params.put("touserId",roomMember.getUserId());
        params.put("type", String.valueOf(RoomMember.ROLE_MEMBER));
        HttpUtils.get().url(coreManager.getConfig().ROOM_MANAGER)
                .params(params)
                .build()
                .execute(new BaseCallback<Void>(Void.class) {

                    @Override
                    public void onResponse(ObjectResult<Void> result) {
                        DialogHelper.dismissProgressDialog();
                        if (result.getResultCode() == 1) {
                            RoomMemberDao.getInstance().updateRoomMemberRole(roomId,roomMember.getUserId(),3);
                            EventBus.getDefault().post(new EventGroupStatus(10000, 0));
                            for (int i = 0; i < sortedList.size(); i++) {
                                if (sortedList.get(i).bean.getUserId()==roomMember.getUserId()){
                                    sortedList.get(i).bean.setRole(RoomMember.ROLE_MEMBER);
                                }
                            }
                            ChangeStatus();
                            Toast.makeText(SetManagerActivity.this, InternationalizationHelper.getString("JXRoomMemberVC_CancelAdministratorSuccess"), Toast.LENGTH_SHORT).show();
                        } else if (!TextUtils.isEmpty(result.getResultMsg())) {
                            ToastUtil.showToast(SetManagerActivity.this, result.getResultMsg());
                        } else {
                            ToastUtil.showToast(SetManagerActivity.this, R.string.tip_server_error);
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        DialogHelper.dismissProgressDialog();
                        Toast.makeText(SetManagerActivity.this, getString(R.string.check_network), Toast.LENGTH_SHORT).show();
                    }
                });
    }

    private void cancelRole(String roomId,RoomMember roomMember, final int role) {
        Integer type;
        switch (role) {
            case RoomMember.ROLE_INVISIBLE:
                type = -1;
                break;
            case RoomMember.ROLE_GUARDIAN:
                type = 0;
                break;
            default:
                Reporter.unreachable();
                return;
        }
        HashMap<String, String> params = new HashMap<>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        params.put("roomId", roomId);
        params.put("touserId", roomMember.getUserId());
        params.put("type", type.toString());
        DialogHelper.showDefaulteMessageProgressDialog(this);

        HttpUtils.get().url(coreManager.getConfig().ROOM_UPDATE_ROLE)
                .params(params)
                .build()
                .execute(new BaseCallback<Void>(Void.class) {

                    @Override
                    public void onResponse(ObjectResult<Void> result) {
                        DialogHelper.dismissProgressDialog();
                        if (result.getResultCode() == 1) {
                            int tipContent;
                            switch (role) {
                                case RoomMember.ROLE_INVISIBLE: // 隐身人
                                    tipContent = R.string.tip_cancel_invisible_success;
                                    //本地更新该成员role值
                                    RoomMemberDao.getInstance().updateRoomMemberRole(roomId,roomMember.getUserId(),3);
                                    break;
                                case RoomMember.ROLE_GUARDIAN: // 监控人
                                    tipContent = R.string.tip_cancel_guardian_success;
                                    break;
                                default:
                                    Reporter.unreachable();
                                    return;
                            }
                            // 保留旧代码，抛出去RoomInfoActivity统一处理，
                            EventBus.getDefault().post(new EventGroupStatus(10000, 0));
                            for (int i = 0; i < sortedList.size(); i++) {
                                if (sortedList.get(i).bean.getUserId()==roomMember.getUserId()){
                                    sortedList.get(i).bean.setRole(RoomMember.ROLE_MEMBER);
                                }
                            }
                            ChangeStatus();
//                            loadData();
                            ToastUtil.showToast(SetManagerActivity.this, tipContent);
                        } else if (!TextUtils.isEmpty(result.getResultMsg())) {
                            ToastUtil.showToast(SetManagerActivity.this, result.getResultMsg());
                        } else {
                            ToastUtil.showToast(SetManagerActivity.this, R.string.tip_server_error);
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        DialogHelper.dismissProgressDialog();
                        ToastUtil.showNetError(SetManagerActivity.this);
                    }
                });
    }

    //改变数据列表状态
    private void ChangeStatus(){
        if (mSortRoomMember != null) {
            mSortRoomMember.clear();
        }
        if (mSortHeadRoomMember!=null){
            mSortHeadRoomMember.clear();
        }
        if (!ListUtil.isListEmpty(sortedList)) {
            mSideBar.searchByFirstStr(sortedList.get(0).getFirstLetter());
        }
        for (int i = 0; i <sortedList.size(); i++) {
            if (sortedList.get(i).getBean().getRole()!=1){
                if (sortedList.get(i).getBean().getRole()==2){
                    mSortHeadRoomMember.add(sortedList.get(i));
                }else {
                    mSortRoomMember.add(sortedList.get(i));
                }
            }
        }
        if (mSortHeadRoomMember.size()>0&&role!=RoomMember.ROLE_INVISIBLE){
            if (mListView.getHeaderViewsCount()==0){
                mListView.addHeaderView(headView);
            }
        }else {
            if (mListView.getHeaderViewsCount()>0){
                mListView.removeHeaderView(headView);
            }
        }
        membersHeadAdapter.notifyDataSetChanged();
        mSetManagerAdapter.notifyDataSetChanged();
    }
    private class SetManagerAdapter extends BaseAdapter implements SectionIndexer {

        private List<BaseSortModel<RoomMember>> sortRoomMember;
        private Context mContext;

        public SetManagerAdapter(Context context,List<BaseSortModel<RoomMember>> sortRoomMember) {
            this.sortRoomMember = new ArrayList<>();
            this.sortRoomMember = sortRoomMember;
            mContext = context;
        }
        @Override
        public int getCount() {
            return sortRoomMember.size();
        }

        @Override
        public Object getItem(int i) {
            return sortRoomMember.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int position, View view, ViewGroup viewGroup) {
            if (view == null) {
                view = LayoutInflater.from(mContext).inflate(R.layout.row_transfer, viewGroup, false);
            }

            TextView catagoryTitleTv = ViewHolder.get(view, R.id.catagory_title);
            ImageView avatar_img = ViewHolder.get(view, R.id.avatar_img);
            TextView roleS = ViewHolder.get(view, R.id.roles);
            TextView nick_name_tv = ViewHolder.get(view, R.id.user_name_tv);

            // 根据position获取分类的首字母的Char ascii值
            int section = getSectionForPosition(position);
            // 如果当前位置等于该分类首字母的Char的位置 ，则认为是第一次出现
            if (position == getPositionForSection(section)) {
                catagoryTitleTv.setVisibility(View.VISIBLE);
                catagoryTitleTv.setText(mSortRoomMember.get(position).getFirstLetter());
            } else {
                catagoryTitleTv.setVisibility(View.GONE);
            }
            RoomMember member = sortRoomMember.get(position).getBean();
            // 设置头像
            AvatarHelper.getInstance().displayAvatar(member.getUserId(), avatar_img, true);

            // 设置职位
//            roleS.setBackgroundResource(R.drawable.bg_role3);
            switch (member.getRole()) {
                case RoomMember.ROLE_OWNER:
                    roleS.setVisibility(View.VISIBLE);
                    roleS.setBackgroundResource(R.drawable.bg_role1);
                    roleS.setText(InternationalizationHelper.getString("JXGroup_Owner"));

                    break;
                case RoomMember.ROLE_MANAGER:
                    roleS.setVisibility(View.VISIBLE);
                    roleS.setText(InternationalizationHelper.getString("JXGroup_Admin"));
                    roleS.setBackgroundResource(R.drawable.bg_role2);

                    break;
                case RoomMember.ROLE_MEMBER:
                    roleS.setVisibility(View.GONE);
                    roleS.setText(InternationalizationHelper.getString("JXGroup_RoleNormal"));
                    roleS.setBackgroundResource(R.drawable.bg_role3);

                    break;
                case RoomMember.ROLE_INVISIBLE:
                    if (RoomMember.ROLE_INVISIBLE==role){
                        roleS.setVisibility(View.VISIBLE);
                        roleS.setText(R.string.role_invisible);
                        roleS.setBackgroundResource(R.drawable.bg_role4);
                    }
                    break;
                case RoomMember.ROLE_GUARDIAN:
                    roleS.setVisibility(View.VISIBLE);

                    roleS.setText(R.string.role_guardian);
                    ViewCompat.setBackgroundTintList(roleS, ColorStateList.valueOf(getResources().getColor(R.color.color_role5)));
                    break;
                default:
                    Reporter.unreachable();
                    roleS.setVisibility(View.GONE);
                    break;
            }
            // 设置昵称
//            nick_name_tv.setText(member.getShowName());
            Friend friend = FriendDao.getInstance().getFriend(coreManager.getSelf().getUserId(),member.getUserId());
            if (friend!=null){
                nick_name_tv.setText(TextUtils.isEmpty(friend.getRemarkName())?friend.getNickName():friend.getRemarkName());
            }else {
                nick_name_tv.setText(member.getShowName());
            }
            return view;
        }

        @Override
        public Object[] getSections() {
            return null;
        }

        @Override
        public int getPositionForSection(int section) {
            for (int i = 0; i < getCount(); i++) {
                String sortStr = mSortRoomMember.get(i).getFirstLetter();
                char firstChar = sortStr.toUpperCase().charAt(0);
                if (firstChar == section) {
                    return i;
                }
            }
            return -1;
        }

        @Override
        public int getSectionForPosition(int position) {
            return mSortRoomMember.get(position).getFirstLetter().charAt(0);
        }
    }

    //显示索引字母
    private void showTextDialog(String s) {
        mTextDialog.setText(s);
        mTextDialog.setVisibility(View.VISIBLE);
        mHandler.removeMessages(0);
        mHandler.sendEmptyMessageDelayed(0, 100);
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    AlphaAnimation aa = new AlphaAnimation(1.0f, 0.0f);//创建一个AlphaAnimation 对象，渐变从1->0
                    aa.setDuration(1000);//设置持续时间
                    aa.setFillAfter(true);
                    mTextDialog.startAnimation(aa);
                    mTextDialog.setVisibility(View.GONE);
                    break;
            }
            super.handleMessage(msg);
        }
    };
}
